package com.dys.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.dys.entity.Course;
import com.dys.service.CourseService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 疾风
 * @ClassName: CourseController
 * @Description: 课程控制器
 * @CreateDate: 2024/12/10
 * @Version: v1.0.0
 */
@Controller
@RequestMapping(value = "/course")
public class CourseController {

    @Autowired
    private CourseService courseService;

    @RequestMapping("/findAll")
    public String findAll(Model model) {
        List<Course> list = courseService.listCourses();
        list.forEach(System.out::println);
        model.addAttribute("courses", list);
        return "index";
    }

    // http://localhost:8088/ 到达导入界面
    @RequestMapping("/importExcel")
    public String importExcel(MultipartFile excelFile) throws Exception {
        ImportParams params = new ImportParams();
        params.setTitleRows(1); // 设置1级标题行为一行
        params.setHeadRows(1); // 设置header标题行为一行

        List<Course> courseList = ExcelImportUtil.importExcel(excelFile.getInputStream(), Course.class, params);
        courseService.batchSave(courseList);
        return "redirect:/course/findAll";
    }

    @RequestMapping(value = "/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        // List<Course> list = new ArrayList<>();
        // for (int i = 0; i < 10; i++) {
        //     Course course = new Course();
        //     course.setCid((long) (i+1));
        //     course.setCname("课程-"+i);
        //     course.setBrief("课程简介-"+i);
        //     course.setPrice(10*(i+1));
        //     course.setOrderNo((long) (Math.random()*1000));
        //     list.add(course);
        // }
        List<Course> list = courseService.listCourses();
        // 生成Excel
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("课程信息列表", "课程信息"), Course.class, list);
        response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode("课程信息列表.xls", "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
    }
}
